import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.HashMap;

public class P2PPartFile extends P2PFile {
	
	public HashMap<Long, byte[]> avChunks = new HashMap<Long, byte[]>();
	
	P2PPartFile(String hash_sb, long size, String filename) throws Exception {
		super();
		this.filename = filename;
		this.sha_sb = hash_sb;
		this.size = size;
		//this.sha_md = SHAChecksum.getMdSHAChecksumString(hash_sb);		
	}

	public void assembleFile() throws IOException {
		FileWriter finalFile = new FileWriter("share/" + this.filename);

		for (long i=0; i<(size-1)/1024; i++) {
			ByteBuffer chunktobyte = ByteBuffer.wrap(avChunks.get(i));
			finalFile.write(chunktobyte.asCharBuffer().array(), (int)i*1024, chunktobyte.capacity());
		}
	}
	
	@Override
	public byte[] getChunk(int num) {
		if (avChunks.containsKey(num)) {
			return avChunks.get(num);
		}
		else
			return null;
	}
	
	public void writeChunk(long num, byte[] data) throws Exception {
		avChunks.put(num, data);
		/*FileWriter fl = new FileWriter("share/" + this.filename);
		ByteBuffer chunktobyte = ByteBuffer.wrap(data);
		fl.write(chunktobyte.asCharBuffer().array(), (int)num*1024, chunktobyte.capacity());*/
		
		File f = new File("share/" + this.filename);
		RandomAccessFile rnd = new RandomAccessFile(f, "rw");
		rnd.seek(num*1024);
		rnd.write(data, 0, data.length);
		rnd.close();
	}

	@Override
	public boolean hasChunk() {
		if (!avChunks.isEmpty())
			return true;
		else
			return false;
	}
	
	public boolean hasChunk(int num) {
		if (avChunks.containsKey(num))
			return true;
		else
			return false;
	}
	
}
